package com.fingard.dsp;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.ConnSet;
import com.fingard.diagnostics.LogFormat;
import com.fingard.dsp.bank.directConfig.BankConfig;
import com.fingard.dsp.linksecure.CertConfig;
import com.fingard.net.IpHelper;
import com.fingard.text.StringHelper;

import java.io.File;
import java.util.Date;

public class DSPSet {
    public String rootDirPath = "";
    public String bankLogsDirPath = "";
    public String bankLogsFormat = "";
    public String dataDirPath = "";

    /**
     * 日志默认主目录
     */
    public String logsMainDir = "";

    public int listenerPort = 0;
    public int webPort = 0;
    public String webDirPath = "";

    public ConnSet dbConnectionSet = null;
    /**
     * 本地数据库文件连接设置
     */
    public ConnSet dbLocalConnSet = null;//本地数据库连接设置
    public boolean enableDbLog = false;//是否启用数据库日志
    public boolean enableHttp = false;//是否启用http识别
    public boolean enableEncrypt = false;//是否启用加密识别
    public CertConfig certConfig =null;
    public String httpReqDefCharset = "";
    
    public boolean autoCreateDbTable = false;//自动创建日志表
    public boolean dbLogOnlySavePath = false;//日志表仅记录日志文件路径
    public String dspCode = "";//dsp代码
    
    /**是否异步启动*/
    public boolean useAsyncRun = false;

    /**
     * 客户代码
     */
    public String customCode = "";
    public String charsetName = "gbk";
    public String encodingWithDspClient = "gbk";
    public boolean simulateWithDB = false;
    public String enableSimulate = "";
    /**
     * DSP后置挡板
     */
    public String bankSimulate = "";
    public int billnum;
    public boolean useDBConn = false;
    public boolean enableBankPayInfo = false;
    public boolean disableAibank = false;
    public int payInfoTableCount = 1;
    public int payInfoActiveDate = 100101;
    public String simulataFilePath="";

    /**
     * 银行接口日志，是否启用异步日志
     */
    public boolean enableAsyncBankLog = false;
    /**
     * 运行模式，如果设置为debug，则控制台会输出更多内容
     */
    public String runMode;


    /**
     * 回单文件下载保存主目录
     */
    public String receiptMainDir = "";
    //回单下载共享目录
    public String receiptShareDir = "";
    //回单文件推送地址
    public String receiptPushServerUrl = "";

    //回单推送数据是否需要加密
    public boolean isEncryptReceiptData=false;

    //回单加密密钥
    public String encryptSecretKey="";


    public String receiptPushType ="";

    /**
     * 回单主服务地址，各DSP将回单文件发送至该DSP
     */
    public String receiptMainHostServer = "";

    /**
     * localhost：本地，即receiptMainDir配置的目录；
     * remoteHost：远程回单主DSP，即receiptMainHostServer配置的DSP服务地址；
     * shareDir：共享目录，即receiptShareDir配置的共享目录
     */
    public String receiptSaveType = "";
    
    /**主控DSP*/
    public String masterServer = "";

    /*
     * 银联特有参数
     * */
    public boolean enableAutoTodayTrans = false;
    public boolean enableAutoHisTrans = false;
    public boolean convertBankArea = false;
    public boolean convertPayState = false;
    public boolean enableCacheCurTrans = false;
    public boolean enableCacheHisTrans = false;

    public boolean enableCheckTransSeqID = false;

    /**
     * 对账码格式，如d20（20位数字），ats6
     */
    public String abstrFormat;
    /**
     * 对账码长度
     */
    public int abstrFormatLen;
    /**
     * 对账码前缀
     */
    public String abstrPrefix;


    /**
     * BankLogs日志第一级目录
     */
    public String bankLogsFirstDir = null;
    public String notifyQueueName = null;

    public boolean disableNIO = false;

    public boolean disableRetryPost = false;

    /**
     * 本地数据库文件
     */
    public String localDbFile = null;
    
    /**org.sqlite.tmpdir*/
    public String sqliteTmpdir = null;

    /**
     * 是否禁用本地数据库(true-是,false或空-否)
     */
    public boolean disableLocalDB = false;

    public boolean enableProxy = false;
    public String proxyIP = "";
    public String proxyPort = "";

    /** 是否逐天查询历史明细 */
    public boolean qryByEachDay7516 = false;

    /**
     * 是否禁用DSPWeb(true-是,false或空-否)
     */
    public boolean disableWeb = false;

    /**
     * 是否启用默认租户配置
     */
    public  String disableTenant="false";
    /**
     * 默认租户10001
     */
    public String tenant="10001";

    /**
     * 行号文件下载保存主目录
     */
    public String codeMainDir = "";
    //行号下载共享目录
    public String codeShareDir = "";
    //行号文件推送地址
    public String codePushServerUrl = "";

    /** 是否启动回单推送定时任务 */
    public String disableTaskTimer = "";
    /** 回单推送定时任务轮询间隔时间，秒 */
    public long taskIntervalSecs = 0;
    /** 分批推送ats的回单文件数量，默认0 */
    public int receiptToAtsBatchNum=0;
    /** 回单推送编码，默认gbk */
    public String receiptToAtsCharset="gbk";
    /** 线程池核心线程数 */
    public int corePoolSize=1;
    /** 线程池最大线程数 */
    public int maximumPoolSize=1;
    /** 主dsp回单文件本地存放路径 */
    public String receiptLocalDir;
    /** 主dsp回单文件共享路径 */
    public String receiptLocalShareDir;
    public String receiptFileSave;

    public String noJoinPostScriptColumn;
    public String noJoinPostScriptText;
    public boolean enableFtpPassiveMode = false;
    public boolean useSleepSimulate = false;
    public double sleepSecondsSimulate = 0;

    public String getDefLocalDbFile() {
        if (StringHelper.isNullOrEmpty(localDbFile)) {
            String dbFile = "{$DSPHOME.Parent}\\db\\bizport.db";
            dbFile = replaceFilePath(dbFile);
            return dbFile;
        } else {
            return localDbFile;
        }
    }

    public void setLocalDbFileIfEmpty(String pPath) {
        if (StringHelper.isNullOrEmpty(localDbFile)) {
            localDbFile = pPath;
            dbLocalConnSet.dbUrl = "jdbc:sqlite:" + localDbFile;
        }
    }

    /**按月取得当前月份的db文件路径*/
    public String getLocalDbFileByMonth(String pTenant, Date pDate) {
        String yearMoAndTenant = Format.Date6YearMonth.format(pDate);
        if(StringHelper.hasAnyChar(pTenant)){
            yearMoAndTenant = yearMoAndTenant + "." + pTenant;
        }
        if(StringHelper.hasAnyChar(localDbFile)){
            int idx = localDbFile.lastIndexOf(".");
            if(idx>0){
                return localDbFile.substring(0, idx) + yearMoAndTenant + localDbFile.substring(idx);
            }else{
                return localDbFile + yearMoAndTenant;
            }
        }else{
            return null;
        }
    }

    public String refreshDspSet(BankConfig tmpConfig) throws Exception {
        String retValue = "";
        useAsyncRun = tmpConfig.getValueAsBool("useAsyncRun");
        dbConnectionSet = tmpConfig.getConnSet("dbConn");
        disableNIO = tmpConfig.getValueAsBool("disableNIO");
        enableHttp = tmpConfig.getValueAsBool("enableHttp");
        enableEncrypt = tmpConfig.getValueAsBool("enableEncrypt");
        disableRetryPost = tmpConfig.getValueAsBool("disableRetryPost");
        enableProxy = tmpConfig.getValueAsBool("enableProxy");
        enableDbLog = tmpConfig.getValueAsBool("enableDbLog");
        enableAsyncBankLog = tmpConfig.getValueAsBool("enableAsyncBankLog");
        runMode = tmpConfig.getValueAsString("runMode");
        if (StringHelper.hasAnyChar(runMode)) {
            runMode = runMode.toLowerCase();
            if ("debug".equals(runMode)) {
                FGBiz.isRunDebugMode = true;
            }
        }
        disableAibank = tmpConfig.getValueAsBool("disableAibank");
        autoCreateDbTable = tmpConfig.getValueAsBool("autoCreateDbTable");
        dbLogOnlySavePath = tmpConfig.getValueAsBool("dbLogOnlySavePath");
        dspCode = tmpConfig.getValueAsString("dspCode");
        customCode = tmpConfig.getValueAsString("customCode");
        proxyIP = tmpConfig.getValueAsString("proxyIP");
        proxyPort = tmpConfig.getValueAsString("proxyPort");
        charsetName = tmpConfig.getValueAsString("charset");
        if (StringHelper.isNullOrEmpty(charsetName)) {
            charsetName = "gbk";
        }
        encodingWithDspClient = tmpConfig.getValueAsString("encodingWithDspClient");
        if (StringHelper.isNullOrEmpty(encodingWithDspClient)) {
            encodingWithDspClient = "gbk";
        }
        
        httpReqDefCharset = tmpConfig.getValueAsString("httpReqDefCharset");
        if (StringHelper.isNullOrEmpty(httpReqDefCharset)) {
        	httpReqDefCharset = "utf-8";
        }
        
        enableSimulate = tmpConfig.getValueAsString("enableSimulate");
        bankSimulate = tmpConfig.getValueAsString("bankSimulate");
        simulataFilePath = tmpConfig.getValueAsString("simulataFilePath");
        billnum = tmpConfig.getValueAsInt("billnum");
        useDBConn = tmpConfig.getValueAsBool("useDBConn");
        simulateWithDB = tmpConfig.getValueAsBool("simulateWithDB");
        enableBankPayInfo = tmpConfig.getValueAsBool("enableBankPayInfo");
        payInfoTableCount = tmpConfig.getValueAsInt("payInfoTableCount") <= 0 ? 1 : tmpConfig.getValueAsInt("payInfoTableCount");
        payInfoActiveDate = tmpConfig.getValueAsInt("payInfoActiveDate") < 0 ? payInfoActiveDate : tmpConfig.getValueAsInt("payInfoActiveDate");
        enableAutoTodayTrans = tmpConfig.getValueAsBool("enableAutoTodayTrans");
        enableAutoHisTrans = tmpConfig.getValueAsBool("enableAutoHisTrans");
        convertBankArea = tmpConfig.getValueAsBool("convertBankArea");
        convertPayState = tmpConfig.getValueAsBool("convertPayState");
        enableCacheCurTrans = tmpConfig.getValueAsBool("enableCacheCurTrans");
        enableCacheHisTrans = tmpConfig.getValueAsBool("enableCacheHisTrans");
        qryByEachDay7516 = tmpConfig.getValueAsBool("qryByEachDay7516");
        bankLogsFormat = tmpConfig.getValueAsString("bankLogsFormat");
        enableCheckTransSeqID = tmpConfig.getValueAsBool("enableCheckTransSeqID");
        notifyQueueName = tmpConfig.getValueAsString("notifyQueueName");
        abstrFormat = tmpConfig.getValueAsString("abstrFormat").toLowerCase();
        abstrPrefix = tmpConfig.getAbstrPrefix();
        if (abstrFormat != null && abstrFormat.startsWith("dl")) {
            try {
                abstrFormatLen = Integer.parseInt(StringHelper.trimStart(abstrFormat, "dl"));
            } catch (Exception ex) {
                retValue += ex.getMessage() + "；";
                abstrFormatLen = -1;
                abstrFormat = "";
                ex.printStackTrace();
            }
        } else if (abstrFormat != null && abstrFormat.startsWith("d")) {
            try {
                abstrFormatLen = Integer.parseInt(StringHelper.trimStart(abstrFormat, "d"));
            } catch (Exception ex) {
                retValue += ex.getMessage() + "；";
                abstrFormatLen = -1;
                abstrFormat = "";
                ex.printStackTrace();
            }
        }

        if (StringHelper.hasAnyChar(bankLogsFormat)) {
            if (bankLogsFormat.toLowerCase().equals(LogFormat.ByHost.toLowerCase())) {
                bankLogsFormat = LogFormat.ByHost;
            } else {
                bankLogsFormat = LogFormat.Default;
            }
        } else {
            bankLogsFormat = LogFormat.Default;
        }
        receiptMainDir = replaceFilePath(tmpConfig.getValueAsString("receiptMainDir"));
        receiptShareDir = tmpConfig.getValueAsString("receiptShareDir");
        receiptPushServerUrl = tmpConfig.getValueAsString("receiptPushServerUrl");
        isEncryptReceiptData = tmpConfig.getValueAsBool("isEncryptReceiptData");
        encryptSecretKey  = tmpConfig.getValueAsString("encryptSecretKey");
        receiptPushType = tmpConfig.getValueAsString("receiptPushType");
        receiptMainHostServer = tmpConfig.getValueAsString("receiptMainHostServer");
        receiptSaveType = tmpConfig.getValueAsString("receiptSaveType");

        int tmpPort = tmpConfig.getValueAsInt("listenerPort");// DomHelper.getSingleElementInnerText(rootElement, );
        if (tmpPort > 0) {
            if (listenerPort > 0 && listenerPort != tmpPort) {
                retValue += "侦听端口listenerPort有变更，需重启才能生效；";
            }
            listenerPort = tmpPort;
        } else {
            retValue += "侦听端口ListenerPort为空";
            System.out.println(retValue);
            retValue += "；";
        }
        String tmpDirPath = tmpConfig.getValueAsString("bankLogsDirPath");// DomHelper.getSingleElementInnerText(rootElement, );
        if (tmpDirPath != null && tmpDirPath.length() > 0) {
            bankLogsDirPath = replaceFilePath(tmpDirPath);
        }

        logsMainDir = tmpConfig.getValueAsString("logsMainDir");
        if (StringHelper.isNullOrEmpty(logsMainDir)) {
            logsMainDir = "{$DSPHOME.Parent}" + File.separator + "logs";
        }
        logsMainDir = replaceFilePath(logsMainDir);

        localDbFile = tmpConfig.getValueAsString("localDbFile");
        localDbFile = replaceFilePath(localDbFile);
        
        sqliteTmpdir = tmpConfig.getValueAsString("sqliteTmpdir");
        sqliteTmpdir = replaceFilePath(sqliteTmpdir);
        
        dbLocalConnSet = new ConnSet();
        dbLocalConnSet.dbDriver = "org.sqlite.JDBC";
        dbLocalConnSet.dbUrl = "jdbc:sqlite:" + localDbFile;

        int port2 = tmpConfig.getValueAsInt("webPort");
        if (port2 > 0) {
            webPort = port2;
        }

        String path2 = tmpConfig.getValueAsString("webDirPath");
        if (path2 != null && path2.length() > 0) {
            webDirPath = replaceFilePath(path2);
        } else {
            webDirPath = this.rootDirPath;
        }

        tmpDirPath = tmpConfig.getValueAsString("dataDirPath");//DomHelper.getSingleElementInnerText(rootElement, "dataDirPath");
        if (tmpDirPath != null && tmpDirPath.length() > 0) {
            dataDirPath = replaceFilePath(tmpDirPath);
        }

        bankLogsFirstDir = "BankLogs";
        if (StringHelper.isNullOrEmpty(FGBiz.localHostIp)) {
            FGBiz.localHostIp = IpHelper.getLocalHostIp();
        }
        if (bankLogsFormat.equals(LogFormat.ByHost)) {
            bankLogsFirstDir += "_" + IpHelper.getLocalHostIp() + "_" + listenerPort;//FGBiz.localHostIp
        }

        disableLocalDB = tmpConfig.getValueAsBool("disableLocalDB");
        disableWeb = tmpConfig.getValueAsBool("disableWeb");

        disableTenant = tmpConfig.getValueAsString("disableTenant");
        tenant = tmpConfig.getValueAsString("tenant");

        codeMainDir = replaceFilePath(tmpConfig.getValueAsString("codeMainDir"));
        codeShareDir = tmpConfig.getValueAsString("codeShareDir");
        codePushServerUrl = tmpConfig.getValueAsString("codePushServerUrl");
        
        masterServer = tmpConfig.getValueAsString("masterServer");

        disableTaskTimer = tmpConfig.getValueAsString("disableTaskTimer");
        if(StringHelper.hasAnyChar(tmpConfig.getValueAsString("taskIntervalSecs"))){
            taskIntervalSecs =  Long.parseLong(tmpConfig.getValueAsString("taskIntervalSecs"));
        }
        if(StringHelper.hasAnyChar(tmpConfig.getValueAsString("receiptToAtsBatchNum"))){
            receiptToAtsBatchNum =  Integer.parseInt(tmpConfig.getValueAsString("receiptToAtsBatchNum"));
        }
        receiptToAtsCharset = tmpConfig.getValueAsString("receiptToAtsCharset");
        if(StringHelper.hasAnyChar(tmpConfig.getValueAsString("corePoolSize"))){
            corePoolSize =  Integer.parseInt(tmpConfig.getValueAsString("corePoolSize"));
        }
        if(StringHelper.hasAnyChar(tmpConfig.getValueAsString("maximumPoolSize"))){
            maximumPoolSize =  Integer.parseInt(tmpConfig.getValueAsString("maximumPoolSize"));
        }
        receiptLocalDir=tmpConfig.getValueAsString("receiptLocalDir");
        receiptLocalShareDir=tmpConfig.getValueAsString("receiptLocalShareDir");
        receiptFileSave=tmpConfig.getValueAsString("receiptFileSave");
        noJoinPostScriptColumn=tmpConfig.getValueAsString("noJoinPostScriptColumn");
        noJoinPostScriptText=tmpConfig.getValueAsString("noJoinPostScriptText");
        enableFtpPassiveMode = tmpConfig.getValueAsBool("enableFtpPassiveMode");
        useSleepSimulate = tmpConfig.getValueAsBool("useSleepSimulate");
        String tmpSleepSecondsSimulate = tmpConfig.getValueAsString("sleepSecondsSimulate");
        if (StringHelper.isNullOrEmpty(tmpSleepSecondsSimulate)) {
            tmpSleepSecondsSimulate = "0";
        }
        sleepSecondsSimulate = Double.parseDouble(tmpSleepSecondsSimulate);
        retValue += "DSPSystem配置文件缓存已刷新。";

        return retValue;
    }

    /**
     * 替换File.separator，替换{$DSPHOME}，替换{$DSPHOME.Parent}
     */
    public static String replaceFilePath(String p_path) {

    	if("/".equals(p_path.trim()) || "\\".equals(p_path.trim())){
			return p_path.trim();
		}
    	
        boolean likePath = false;
        if (p_path.contains("{$DSPHOME}") || p_path.contains("{$DSPHOME.Parent}") || p_path.contains(":") || p_path.startsWith("/") || p_path.startsWith("\\")) {
            likePath = true;
        } else if (p_path.contains("\\") && p_path.contains("/")) {
            likePath = true;
        }
        if (likePath) {
            return StringHelper.trimEndFileSp(p_path.replace("\\", File.separator).replace("/", File.separator).replace("{$DSPHOME}", FGBiz.DSPHOME).replace("{$DSPHOME.Parent}", FGBiz.DSPHOME_Parent));
        } else {
            return p_path;
        }
    }
}
